import cv2
import numpy as np
import os
import argparse

# 读取模板图片
template_wan = cv2.imread("images/option/wan.png", cv2.IMREAD_COLOR)
template_tianen = cv2.imread("images/option/tianen.png", cv2.IMREAD_COLOR)
template_suo = cv2.imread("images/option/suo.png", cv2.IMREAD_COLOR)
template_dashi = cv2.imread("images/option/dashi.png", cv2.IMREAD_COLOR)
template_libao = cv2.imread("images/option/libao.png", cv2.IMREAD_COLOR)
template_baiye = cv2.imread("images/option/baiye.png", cv2.IMREAD_COLOR)
template_fenshen = cv2.imread("images/option/fenshen.png", cv2.IMREAD_COLOR)

# 模板列表和对应的计数器
templates = [template_wan, template_tianen, template_suo, template_dashi, template_libao, template_baiye, template_fenshen]
template_names = ["万象", "天恩", "柚子", "大师", "礼包", "白夜", "蓝星"]
template_names_en = ["wan", "tianen", "suo", "dashi", "libao", "baiye", "fenshen"]
counts = {name: 0 for name in template_names}

# 日志动作计数器
log_actions = ["开金包", "开始打牌", "开始开包"]
action_counts = {action: 0 for action in log_actions}

# 每种牌的开始打牌和开始开包计数器
card_play_counts = {}
card_open_counts = {}

# 升级邀请函出的彩卡计数器
invitation_counts = {name: 0 for name in template_names}
total_invitation_count = 0

def is_valid_date(date_str):
    try:
        # 检查日期格式是否为 YYYYMMDD
        if len(date_str) == 8 and date_str.isdigit():
            return True
        return False
    except ValueError:
        return False

def filter_files_by_date(files, date):
    if date is None:
        return files
    filtered_files = []
    for file in files:
        if file.endswith(('.png', '.jpg', '.jpeg')):
            file_date = file[:8]
            if file_date == date:
                filtered_files.append(file)
        elif file.endswith('.log'):
            parts = file.split('_')
            if len(parts) > 1:
                log_date = parts[1].replace('.log', '').replace('-', '')
                if log_date == date:
                    filtered_files.append(file)
    return filtered_files

def main():
    global counts, action_counts, card_play_counts, card_open_counts, invitation_counts, total_invitation_count

    parser = argparse.ArgumentParser(description='统计彩卡和日志数据')
    parser.add_argument('--date', type=str, help='指定统计的日期，格式为 YYYYMMDD', default=None)
    args = parser.parse_args()

    if args.date and not is_valid_date(args.date):
        print("日期格式不正确，请使用 YYYYMMDD 格式。")
    else:
        # 遍历 tem 目录下的所有图片
        tem_dir = "images/option/tem"
        image_files = os.listdir(tem_dir)
        filtered_image_files = filter_files_by_date(image_files, args.date)
        for filename in filtered_image_files:
            if filename.endswith(('.png', '.jpg', '.jpeg')):
                image_path = os.path.join(tem_dir, filename)
                image = cv2.imread(image_path, cv2.IMREAD_COLOR)

                # 进行模板匹配
                for i, template in enumerate(templates):
                    result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
                    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

                    # 设置匹配阈值
                    threshold = 0.7
                    if max_val >= threshold:
                        counts[template_names[i]] += 1
                        break

        # 计算总匹配数量
        total_count = sum(counts.values())

        # 遍历 log 文件夹下的所有日志文件
        log_dir = "logs/tem"
        log_files = os.listdir(log_dir)
        filtered_log_files = filter_files_by_date(log_files, args.date)
        current_card = None
        for filename in filtered_log_files:
            if filename.endswith(('.log')):
                log_path = os.path.join(log_dir, filename)
                try:
                    with open(log_path, 'r', encoding='utf-8') as file:
                        for line in file:
                            for action in log_actions:
                                if action in line:
                                    action_counts[action] += 1
                                    if action == "开始打牌":
                                        # 解析牌名
                                        current_card = line.split("开始打牌")[1].strip()
                                        card_play_counts[current_card] = card_play_counts.get(current_card, 0) + 1
                                    elif action == "开始开包":
                                        if current_card:
                                            card_open_counts[current_card] = card_open_counts.get(current_card, 0) + 1
                            if "邀请函" in line:
                                total_invitation_count += 1
                                for i, name_en in enumerate(template_names_en):
                                    if name_en in line:
                                        invitation_counts[template_names[i]] += 1
                                        break

                except Exception as e:
                    print(f"读取日志文件 {log_path} 时出错: {e}")

        # 打印日志动作统计结果
        for action, count in action_counts.items():
            print(f"{action}: {count} 次")
        # 打印每个模板对应的图片数量和百分比
        print(f"彩卡总计: {total_count} 张")
        # 计算彩卡率
        if action_counts["开金包"] > 0:
            card_rate = (total_count / action_counts["开金包"]) * 100
            print(f"彩卡率: {card_rate:.2f}%")
        else:
            print("彩卡率: 0.00%")

        # 计算不同牌的暴毙率
        print("\n不同牌的暴毙率统计：")
        for card in card_play_counts.keys():
            play_count = card_play_counts[card]
            open_count = card_open_counts.get(card, 0)
            if play_count > 0:
                death_rate = ((play_count - open_count) / play_count) * 100
                print(f"{card} 打牌次数: {play_count} 次，暴毙率: {death_rate:.2f}%")
            else:
                print(f"{card} 打牌次数: {play_count} 次，暴毙率: 0.00%")

        # 打印整合后的彩卡统计结果
        print("\n彩卡统计（包含邀请函出卡情况）：")
        for name in template_names:
            count = counts[name]
            invitation_count = invitation_counts[name]
            if total_count > 0:
                percentage = (count / total_count) * 100
            else:
                percentage = 0.0
            if total_invitation_count > 0:
                invitation_percentage = (invitation_count / total_invitation_count) * 100
            else:
                invitation_percentage = 0.0
            print(f"{name}: 总数 {count} 张（占比: {percentage:.2f}%），函出 {invitation_count} 张（占比: {invitation_percentage:.2f}%）")

if __name__ == "__main__":
    main()
# 使用示例: python count.py --date 20250822
# 不指定日期则统计所有数据: python count.py
